import java.io.*;
import java.net.*;

/*Parametri da passare: DatagramSocket di aknownledgment
 * 						array di celle da modificare
 * 						riceve massimo una array di 100000		
 * 
 */
public class DaemonReceiver{
	
		//ATTRIBUTI CLASSE 
		DatagramSocket serverDR;
		Cell[] cella;

		//METODI CLASSE
		
		public DaemonReceiver (DatagramSocket ACKsocket, Cell[] cell) {
				this.serverDR = ACKsocket;
				this.cella = cell;
		}
		
		public void runDR() {
			byte[] receiveData = new byte[10000];
			System.out.println("DaemonReceiver started");
			boolean fine = false;
			while(!fine) {
				try {
					DatagramPacket receivedPacket = new DatagramPacket(receiveData, receiveData.length);
					this.serverDR.receive(receivedPacket);
					Packet pkt = new Packet(receivedPacket.getData());
					ParallelDR parallelDR = new ParallelDR(receivedPacket, this.cella);
					Thread thread = new Thread(parallelDR);
					thread.run();
					if (pkt.getIDPacket() == 65535)
						fine = true;
					
				} catch(IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		private class ParallelDR implements Runnable {
			
			private DatagramPacket dGram;
			private Cell[] cella;
			
			//METODO COSTRUTTORE
			public ParallelDR(DatagramPacket client, Cell[] cell){	
				this.dGram = client;
				this.cella = cell;
				
			}
			
			public void run(){                                        //Ha ricevuto un ACK, lo trasforma in oggetto Packet
				try {												  //mette a null la cella con l'indice del pacchetto ACK
					Packet rec = new Packet(dGram.getData());
					//System.out.println(rec.getIDPacket());
					if ((rec.getIDPacket() < 65530)) {
						this.cella[rec.getIDPacket()].setTime(1);
						System.out.println("DaemonRiceiver ACKed: "+rec.getIDPacket() );
					}
					if (rec.getIDPacket() == 65535){
						for (int i = 0; i < cella.length; i++){
							if (this.cella[i].getTime() != 1){
								this.cella[i].setTime(1);
								System.out.println("DaemonRiceiver ACKed: 65535");
			
							}
						}		
					}
						
				}catch(Exception e) {
	    			e.printStackTrace();
				}			
	        }
		}
}
